//
//  ZFLoginViewController.m
//  HappilyLoan
//
//  Created by zainishenbian on 2017/3/21.
//  Copyright © 2017年 zongqingxiangqian. All rights reserved.
//

#import "ZFLoginViewController.h"
#import "ZFRegisterViewController.h"//注册
#import "ZFVerifyLoginViewController.h"//验证码登录
#import "ZFForgetPswViewController.h"//忘记密码
#import "ZFLoginHttpRequest.h"
#import "ZFHeader.h"
#import "JPUSHService.h"

@interface ZFLoginViewController ()<UITextFieldDelegate>
@property(nonatomic,strong)AlertBoxView *alertBox;
@end

@implementation ZFLoginViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"loginView"];
    self.navigationController.navigationBarHidden = NO;
    
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    if ([delegate.completeRegister isEqualToString:@"完成注册"]) {
        
        delegate.completeRegister = @"";
        [self dismissViewControllerAnimated:NO completion:nil];
    }
}
- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self initData];
    
    [_loginButton setShadowWidth:2 shadowHeight:2 shadowColor:Main_Color1 radius:10];
    [self.view addSubview:self.alertBox];
    
}

- (void)initData
{
    _thirdLoginView.hidden = YES;
    _codeLoginButton.hidden = YES;
    
    _loginButton.backgroundColor = Main_Color1;
    _logo.layer.cornerRadius = 10;
    _logo.layer.masksToBounds = YES;
}

#pragma mark ———— textfield delegate
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

    NSUInteger proposedNewLength = textField.text.length - range.length + string.length;

    if (textField == _phoneTF) {
        
        if (proposedNewLength > 11) {
            
            return NO;
        }
    }
    if (textField == _pswTF) {
        NSUInteger lengthOfString = string.length;  //lengthOfString的值始终为1
        for (NSInteger loopIndex = 0; loopIndex < lengthOfString; loopIndex++) {
            unichar character = [string characterAtIndex:loopIndex]; //将输入的值转化为ASCII值（即内部索引值），可以参考ASCII表
            // 48-57;{0,9};65-90;{A..Z};97-122:{a..z}
            if (character < 48) return NO; // 48 unichar for 0
            if (character > 57 && character < 65) return NO; //
            if (character > 90 && character < 97) return NO;
            if (character > 122) return NO;
            
        }
        // Check for total length
        //NSUInteger proposedNewLength = textField.text.length - range.length + string.length;
        if (proposedNewLength > 16) {
            return NO;//限制长度
        }
    }
    return YES;
}

#pragma mark ———— button的点击事件
//注册
- (IBAction)registerClick:(id)sender {
    
    ZFRegisterViewController *registerVC = [ZFRegisterViewController new];
    [self.navigationController pushViewController:registerVC animated:YES];
}
//登录
- (IBAction)loginClick:(id)sender {
    
    if (self.phoneTF.text.length == 0) {
        [_alertBox appearAndDisappearAlertWithString:@"手机号不能为空"];

        return;
    }
    else if (self.pswTF.text.length == 0) {
        [_alertBox appearAndDisappearAlertWithString:@"登录密码不能为空"];
        return;
    }
    
       if ([ZFPulicAPI replaceBlank:_phoneTF.text].length >= 11) {
        
        if ([ZFLoginConfig isValidatePhone:[ZFPulicAPI replaceBlank:_phoneTF.text]]) {
            
            if ([ZFPulicAPI replaceBlank:_pswTF.text].length >= 6 ) {
                
                [ZFLoginHttpRequest requestLoginPhone:[ZFPulicAPI replaceBlank:_phoneTF.text] pwd:[ZFPulicAPI replaceBlank:_pswTF.text] sucessBlock:^(NSDictionary *dict) {
                    
                    if ([dict[@"is_alert"] integerValue] == 1) {
                        
                        [_alertBox appearAndDisappearAlertWithString:dict[@"msg"]];
                    }
                    if ([dict[@"code"] integerValue] == 1) {
                        
                         if ([ZFLoginConfig judgeIsFirstEnterApp] == YES) {
                            
                            AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
                            delegate.isFirstEnterApp = NO;
//
                             [MobClick profileSignInWithPUID:@"UserID"];
                             [MobClick event:@"UserID" label:@"setPass"];
                             [JPUSHService setAlias:[[NSUserDefaults standardUserDefaults] objectForKey:@"phone"] callbackSelector:nil object:nil];
                            [self.navigationController popToRootViewControllerAnimated:YES];
                        }
                        else
                        {
                            [self dismissViewControllerAnimated:YES completion:nil];
                        }
                    }
                    else
                    {
                        [_alertBox appearAndDisappearAlertWithString:[NSString stringWithFormat:@"%@",dict[@"msg"]]];
                    }
                    
                } failureBlock:^(NSInteger failSign) {
                    [_alertBox appearAndDisappearAlertWithString:@"网络连接失败"];
                }];
            }
        }else{
            [_alertBox appearAndDisappearAlertWithString:@"请填写正确的手机号"];
        }
    }else{
        [_alertBox appearAndDisappearAlertWithString:@"请填写正确的手机号或密码"];
    }
}

//忘记密码
- (IBAction)forgetPswClick:(id)sender {
    
    ZFForgetPswViewController *forgetVC = [ZFForgetPswViewController new];
    [self.navigationController pushViewController:forgetVC animated:YES];
}
//验证码登录
- (IBAction)VerifyLoginClick:(id)sender {
    
    ZFVerifyLoginViewController *verifyLoginVC = [ZFVerifyLoginViewController new];
    [self.navigationController pushViewController:verifyLoginVC animated:YES];
}
//是否显示密码
- (IBAction)isShowPsw:(id)sender {
    
    static BOOL isShow = NO;
    
    if (isShow == YES) {
        
        _pswTF.secureTextEntry = NO;
        [_earButton setImage:[UIImage imageNamed:@"图层-1"] forState:UIControlStateNormal];
    }
    else
    {
        _pswTF.secureTextEntry = YES;
        [_earButton setImage:[UIImage imageNamed:@"yanjing"] forState:UIControlStateNormal];
    }
    isShow = !isShow;
}
//返回
- (IBAction)back:(id)sender {
    
    if ([ZFLoginConfig judgeIsFirstEnterApp] == YES) {
        
        [self.navigationController popToRootViewControllerAnimated:YES];
        AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        delegate.isFirstEnterApp = NO;
    }
    else
    {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"loginView"];
}
- (AlertBoxView *)alertBox
{
    if (!_alertBox) {
        _alertBox = [[AlertBoxView alloc] init];
    }
    return _alertBox;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
